package timing.ukulele.portal.util;

import org.springframework.util.StringUtils;
import timing.ukulele.common.util.CryptoUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class DecryptUtil {
    public static String privateKey;

    public static String decryptPassword(String encryptString) {
//        System.out.println("解密前：" + encryptString);
        String pbs = getPrivateKey();
//        System.out.println("私钥:" + pbs);
        try {
            String result = CryptoUtils.decryptByRSA(pbs, encryptString);
//            System.out.println("解密后：" + result);
            return result;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String getPrivateKey() {
        if (StringUtils.hasText(privateKey))
            return privateKey;
        InputStream ins = DecryptUtil.class.getClassLoader().getResourceAsStream("privateKey.txt");
        if (ins != null) {
            try {
                BufferedReader tBufferedReader = new BufferedReader(new InputStreamReader(ins));
                StringBuilder tStringBuffer = new StringBuilder();
                String sTempOneLine;
                while ((sTempOneLine = tBufferedReader.readLine()) != null) {
                    tStringBuffer.append(sTempOneLine);
                }
                String str = tStringBuffer.toString();
                privateKey = str.replaceAll("[\t\n\r]", "");
            } catch (Exception ex) {
                ex.printStackTrace();
                privateKey = null;
            }
        } else {
            privateKey = null;
        }
        return privateKey;
    }
}
